/**
##############################################################################

DOCOMO Innovations, Inc.

Copyright © 2011 DOCOMO Innovations, Inc. All rights reserved.

 

Date of Preparation: 08/01/2011

Contact: kozat@docomoinnovations.com

 

All intellectual property rights related to this software are vested in DOCOMO Innovations.

DOCOMO Innovations is under no obligation to maintain or support the software.

Neither DOCOMO Innovations nor its employees are responsible for any damage or loss resulting from the use of the software.

##############################################################################
 */

package umich.infinity.proxy;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;

import umich.infinity.thrift.Attr;

/**
 * Expose the interface to write log messages to log files.
 * 
 * @author stgyd
 *
 */
public class LogManager {
	
	public static final String TAG = "LogManager";
	public LogManager() {
		
		File f =  new File (Para.CacheRoot + Para.CacheLogDir);
		if (!f.exists()) f.mkdirs();
	}
		
	/** Write data the local log cache
	    ** 
	    * @param uid the uid of the user
	    ** @param path the full path of the file in Infintiy     
	    ** @param offset offset from the begin of the file, should be multiple of chunk size
	    ** @param size size should be multiple of block size
	    ** @param buf the buf with the actual content
	    ** @return 0 if success. non-zero if error happens.
	    */
	public int write(String uid, String path, long offset, long size, ByteBuffer buf) {
		String fn =  Util.logFileName(uid, path);
		
		Util.myDebug(TAG, path+" "+offset+","+size);
		
		File f = new File(fn);
		
		if (!f.exists()) {
			f.getParentFile().mkdirs();
		}

		try {
			RandomAccessFile raf = new RandomAccessFile(f, "rw");

			// Extend the original cache file if it is too small
			if (raf.length() < (offset + size)) {
				raf.setLength(offset + size);
			}

			raf.seek(offset);

			if (buf!=null) {
				raf.write(buf.array(), 0, (int) size);
			}

			raf.close();
		} catch (IOException x) {
			Util.myDebug(TAG, x.toString());
		}
		
		return 0;
	}
}
